﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadVinaglue.Models;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Utility;
using LeadVinaglue.Helpers;
using LeadVinaglue.Repository;

namespace LeadVinaglue.Controllers
{
    public class BaseController : Controller
    {
        LeadVinaglueEntities entities = new LeadVinaglueEntities();
        public static string BannerImageUrl = ConfigurationManager.AppSettings["BannerImagesURL"].ToString();       

        // Setup commont function
        public void SetupCommon(BaseViewModel  model)
        {
            GetAdScripts(ref model);
            model.Menu = GetMenuConfig(model.PageName);
            model.BreadCrumb = GetAllNavigationLink(model);
        }

        #region BreadCrumbs
        private List<NavigationLink> GetAllNavigationLink(BaseViewModel model)
        {
            List<NavigationLink> list = new List<NavigationLink>();

            switch (model.PageName)
            {
                case LeadConstant.CATEGORY:
                    {
                        list = BuildCategoryLink(model.CategoryId, model.SubCategoryId);
                        break;
                    }
                case LeadConstant.PRODUCTINFO:
                    {
                        list = BuildProductDetailLink(model.ProductId);
                        break;
                    }
                case LeadConstant.SEARCH:
                    {
                        list = BuildSearchLink(model.FilterValue);
                        break;
                    }
                default:
                    {
                        break;
                    }
            }

            return list;
        }
        private List<NavigationLink> BuildCategoryLink(int categoryId, int subCategoryId)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            NavigationLink item;

            // Add Home
            item = new NavigationLink();
            item.LinkText = "Trang chủ";
            item.LinkUrl = "/";
            list.Add(item);

            if (subCategoryId > 0)
            {
                var sub = new SubCategoryRepository().GetSingle(subCategoryId);
                var cat = new CategoryRepository().GetSingle(categoryId);

                // Add category
                item = new NavigationLink();
                item.LinkText = cat.Name;
                item.LinkUrl = string.Format("/{0}/tat-ca-tai-lieu.{1}", StringClearFormat.ClearSpecials(cat.Name), cat.ID);
                list.Add(item);

                // Add sub
                item = new NavigationLink();
                item.LinkText = sub.Name;
                item.LinkUrl = string.Empty; // string.Format("/{0}/{1}.{2}.{3}", StringClearFormat.ClearSpecials(cat.Name), StringClearFormat.ClearSpecials(sub.Name), cat.ID, sub.ID);
                list.Add(item);
            }
            else
            {
                var cat = new CategoryRepository().GetSingle(categoryId);
                
                // Add category
                item = new NavigationLink();
                item.LinkText = cat.Name;
                item.LinkUrl = string.Empty;
                list.Add(item);
            }

            return list;
        }


        private List<NavigationLink> BuildSearchLink(string keywords)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            NavigationLink item;

            // Add Home
            item = new NavigationLink();
            item.LinkText = "Trang chủ";
            item.LinkUrl = "/";
            list.Add(item);

            // Add Searc
            item = new NavigationLink();
            item.LinkText = string.Format("Tìm kiếm \"{0}\"", keywords);
            item.LinkUrl = string.Empty;
            list.Add(item);

            return list;
        }

        private List<NavigationLink> BuildProductDetailLink(int productId)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            NavigationLink item;

            // Add Home
            item = new NavigationLink();
            item.LinkText = "Trang chủ";
            item.LinkUrl = "/";
            list.Add(item);

            var product = new ProductRepository().GetSingle(productId);
            var sub = new SubCategoryRepository().GetSingle(product.SubCategoryID.Value);
            var cat = new CategoryRepository().GetSingle(sub.CategoryID);

            // Add category
            item = new NavigationLink();
            item.LinkText = cat.Name;
            item.LinkUrl = string.Format("/{0}/tat-ca-tai-lieu.{1}", StringClearFormat.ClearSpecials(cat.Name), cat.ID);
            list.Add(item);

            // Add sub
            item = new NavigationLink();
            item.LinkText = sub.Name;
            item.LinkUrl = string.Format("/{0}/{1}.{2}.{3}", StringClearFormat.ClearSpecials(cat.Name), StringClearFormat.ClearSpecials(sub.Name), cat.ID, sub.ID);
            list.Add(item);

            // Add product title
            item = new NavigationLink();
            item.LinkText = product.Title;
            item.LinkUrl = string.Empty;
            list.Add(item);


            return list;
        }
        #endregion

        #region Private Methods
        private List<NavigationMenu> GetMenuConfig(string pageType)
        {
            List<NavigationMenu> list = new List<NavigationMenu>();
            NavigationConfig categoryConfig=new NavigationConfig();

            // 2: Category caching
            string CategoryCachingMenuConfig = "CategoryListConfig";
            int CategoryCachingMenuTimer = 10;
            if (System.Web.HttpContext.Current.Cache[CategoryCachingMenuConfig] != null)
                categoryConfig = (NavigationConfig)System.Web.HttpContext.Current.Cache[CategoryCachingMenuConfig];
            if (System.Web.HttpContext.Current.Cache[CategoryCachingMenuConfig] == null)
            {
                categoryConfig = LeadTools.Deserialize(System.Web.HttpContext.Current.Server.MapPath(@"/Configs/CategoryListConfig.xml"), categoryConfig);
                System.Web.HttpContext.Current.Cache.Insert(CategoryCachingMenuConfig, categoryConfig, null, DateTime.Now.AddMinutes(CategoryCachingMenuTimer), TimeSpan.Zero);
            }

            // Set to list
            foreach (var item in categoryConfig.NavigationItems)
            {
                NavigationMenu model = new NavigationMenu();
                model.IsCurrentTab = false;
                model.LinkText = item.ItemName;
                model.LinkUrl = item.ItemLink;
                model.SubMenu = GetSubMenu(item.SubItems);
                list.Add(model);
            }

            return list;
        }
        private List<NavigationLink> GetSubMenu(List<NavigationItem> subItems)
        {
            List<NavigationLink> list = new List<NavigationLink>();

            // Check conditions
            if (subItems != null)
            {
                foreach (var item in subItems)
                {
                    NavigationLink link = new NavigationLink();
                    link.LinkText = item.ItemName;
                    link.LinkUrl = item.ItemLink;

                    list.Add(link);
                }
            }

            return list;
        }

        private void GetAdScripts(ref BaseViewModel model)
        {
            List<BannerModel> filters = GetBanners(model.PageName);

            if (filters != null && filters.Count > 0)
            {
                // Sky Ads
                model.SkyAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.SKY).ToList(), "skypAds");

                // Lead/Middle Ads
                model.LeadAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.LEADERBOARD).ToList(), "leadAds");

                // Bottom Ads
                model.BottomAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.BOTTOM).ToList(), "btmAds");

                // Popup Ads
                model.MiddleAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.MIDDLE).ToList(), "midAds");
                
                // TowerAds
                var list = filters.Where(c => c.PositionId == PositionConstant.TOWER).ToList();

                if (list!=null)
                {
                    if (list.Count >= 16)
                    {
                        for (int i = 1; i <= 6; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 3).Take(3).ToList(), string.Format("TAZone{0}", i));
                        }
                    }
                    else if (list.Count >= 11)
                    {
                        for (int i = 1; i <= 6; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 2).Take(2).ToList(), string.Format("TAZone{0}", i));
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= list.Count; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 1).Take(1).ToList(), string.Format("TAZone{0}", i));
                        }
                    }

                }

            }
        }

        private List<BannerModel> GetBanners(string pageType)
        {
            List<BannerModel> list=new List<BannerModel>();

            var items = (from c in entities.Banners.AsEnumerable()
                    where c.Active &&  LeadTools.StartOfDay(c.StartDate.Value) <= DateTime.Now && LeadTools.EndOfDay(c.EndDate.Value) >= DateTime.Now
                    select c).ToList();

            switch (pageType)
            {
                case LeadConstant.HOME:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnHomePage == true).ToList();
                        break;
                    }
                case LeadConstant.CATEGORY:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnCategoryPage == true).ToList();
                        break;
                    }
                case LeadConstant.ZONE:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnZonePage == true).ToList();
                        break;
                    }
                case LeadConstant.PRODUCTINFO:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnDetailPage == true).ToList();
                        break;
                    }
                default:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnOtherPage == true).ToList();
                        break;
                    }
            }

            // Add items
            foreach (var item in items.OrderByDescending(c => c.ID))
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.WebsiteUrl = item.WebsiteUrl;
                model.Width = Convert.ToInt32(item.Width);
                model.Height = Convert.ToInt32(item.Height);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }

        private string BuildSkyAdScripts(List<BannerModel> list, string skyName)
        {
            string script = string.Empty;

            if (list != null && list.Count > 0)
            {
                script = "<script language=\"javascript\" type=\"text/javascript\">";
                script += string.Format("{0} = new Banner('{1}');", skyName, skyName); 

                int i = 0;
                foreach (var item in list)
                {
                    i++;
                    if (!string.IsNullOrEmpty(item.FlashUrl))
                    {
                        if (!string.IsNullOrEmpty(item.WebsiteUrl))
                            script += string.Format("{0}.add(\"FLASH\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.FlashUrl), i, item.Height, item.Width, item.WebsiteUrl);
                        else
                            script += string.Format("{0}.add(\"FLASH\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.FlashUrl), i, item.Height, item.Width, "##");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.WebsiteUrl))
                            script += string.Format("{0}.add(\"IMAGE\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.ImageUrl), i, item.Height, item.Width, item.WebsiteUrl);
                        else
                            script += string.Format("{0}.add(\"IMAGE\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.ImageUrl), i, item.Height, item.Width, "##");
                    }
                }

                script += string.Format("document.write({0});", skyName);
                script += string.Format("{0}.start();", skyName);
                script += "</script>";
            }

            return script;
        }

        #endregion
    }
}
